package com.way.demo.sort;

import java.util.Arrays;

/**
 * @author lipingwei
 * @create 2023-03-09 21:20
 *
 * 归并排序 时间复杂度为： O(nlogn)
 *
 *
 *
 */
public class MergeSort2 {
    public static void main(String[] args) {
        int[] arr={8,4,5,7,1,4,6,2};
        int[] tmp = new int[arr.length];

        mergeSor(arr,0,arr.length-1,tmp);

        System.out.println(Arrays.toString(arr));


    }

    //归并排序先分解
    public static void mergeSor(int[] arr, int left,int right,int[] tmp){
        if(left<right){
            int mid = (left+right)/2;
            mergeSor(arr,left,mid,tmp);
            mergeSor(arr,mid+1,right,tmp);
            merge(arr,left,right,mid,tmp);

        }

    }

    public static void merge(int[]arr,int left,int right,int mid, int[]tmp){
        int i=left;
        int j=mid+1;
        int t=0;

        while(i<=mid && j<=right){
            if(arr[i]<=arr[j]){
                tmp[t]=arr[i];
                t++;
                i++;
            }else {
                tmp[t]=arr[j];
                t++;
                j++;
            }
        }

        while(i<=mid){
            tmp[t]=arr[i];
            t++;
            i++;
        }
        while (j<=right){
            tmp[t]=arr[j];
            t++;
            j++;
        }

        //拷贝数据
        t=0;
        int leftTmp=left;
        while (leftTmp<=right){
            arr[leftTmp]=tmp[t];
            leftTmp++;
            t++;
        }


    }

}
